/*************************************************************************
	> File Name: 1.add.c
	> Author: 
	> Mail: 
	> Created Time: 2021年01月19日 星期二 18时46分11秒
 ************************************************************************/

#include "head.h"

#define INS 5

struct Num {
    int now;
    int sum;
};

struct Num *share_memory;

void do_add(int x) {
    while (1) {
        if (share_memory->now > 100) {
            shmdt(share_memory);
            break;
        }
        share_memory->sum += share_memory->now;
        share_memory->now++;
        printf("<%d> now = %d, sum = %d\n", x, share_memory->now, share_memory->sum);
        usleep(100);
    }
}

int main() {
    pid_t pid;
    int x = 0, shmid;
    key_t key = ftok(".", 2021);
    if ((shmid = shmget(key, sizeof(struct Num), IPC_CREAT | IPC_EXCL | 0666)) < 0) {
        perror("shmget()");
        exit(1);
    }
    share_memory = (struct Num *)shmat(shmid, NULL, 0);
    if (share_memory < 0) {
        perror("share_memory");
        exit(1);

    }
    share_memory->now = 0;
    share_memory->sum = 0;
    printf("before fork\n");
    for (int i = 1; i <= INS; i++) {
        if ((pid = fork()) < 0) {
            perror("fork()");
            exit(1);
        }
        x = i;
        if (pid == 0) break;
    }
    if (pid == 0) {
        do_add(x);
    } else {
        for (int i = 1; i <= INS; i++) {
            wait(NULL);
        }
        printf("share_memory->sum = %d\n", share_memory->sum);   
        shmdt(share_memory);
    }

    return 0;
}
